// pages/my-orders/my-orders.js
const api = require('../../utils/api.js')
const config = require('../../utils/config.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({
    data: {
        orders: [],
        statusFilter: '',
        statusText: {
            pending: '待处理',
            processing: '处理中',
            completed: '已完成',
            rejected: '已拒绝'
        },
        statusClass: config.orderStatus,
        page: 1,
        hasMore: true
    },

    onLoad() {
        // 检查登录状态
        if (!app.isLoggedIn()) {
            wx.showModal({
                title: '需要登录',
                content: '查看报修记录需要先登录',
                confirmText: '去登录',
                cancelText: '返回',
                success: res => {
                    if (res.confirm) {
                        wx.redirectTo({
                            url: '/pages/login/login'
                        })
                    } else {
                        wx.switchTab({
                            url: '/pages/index/index'
                        })
                    }
                }
            })
            return
        }

        this.loadOrders()
    },

    onShow() {
        // 刷新列表
        this.refreshOrders()
    },

    onReachBottom() {
        if (this.data.hasMore) {
            this.loadMore()
        }
    },

    onPullDownRefresh() {
        this.refreshOrders()
    },

    // 加载报修记录
    loadOrders() {
        wx.showLoading({ title: '加载中...' })

        const params = {
            openid: app.globalData.openid,
            status: this.data.statusFilter,
            page: this.data.page,
            pageSize: config.pageSize
        }

        api.getRepairOrders(params).then(res => {
            const orders = res.list || res

            // 格式化时间
            orders.forEach(order => {
                order.created_at = util.relativeTime(util.safeDate(order.created_at).getTime())
            })

            this.setData({
                orders: this.data.page === 1 ? orders : [...this.data.orders, ...orders],
                hasMore: orders.length >= config.pageSize
            })
        }).catch(err => {
            console.error('加载报修记录失败', err)
        }).finally(() => {
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },

    // 刷新列表
    refreshOrders() {
        this.setData({
            page: 1,
            hasMore: true
        })
        this.loadOrders()
    },

    // 加载更多
    loadMore() {
        this.setData({
            page: this.data.page + 1
        })
        this.loadOrders()
    },

    // 状态筛选
    filterByStatus(e) {
        const status = e.currentTarget.dataset.status

        this.setData({
            statusFilter: status,
            page: 1,
            hasMore: true
        })

        this.loadOrders()
    },

    // 查看工单详情
    viewOrderDetail(e) {
        const orderId = e.currentTarget.dataset.id

        wx.navigateTo({
            url: `/pages/order-detail/order-detail?orderId=${orderId}`
        })
    },

    // 返回首页
    goToIndex() {
        wx.switchTab({
            url: '/pages/index/index'
        })
    }
})
